package com.iwop.moto.schedule;

import com.iwop.moto.controller.BaseController;
import com.iwop.moto.dao.PayPassCodeDao;
import com.iwop.moto.model.FErrorLog;
import com.iwop.moto.service.FErrorLogService;
import com.iwop.moto.service.MPaymentService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * #author chenzq
 * #create 2017-01-17-0:38
 */
@Component
public class PayPasswordSchedule {

    Logger logger = Logger.getLogger(PayPasswordSchedule.class);

    @Autowired
    MPaymentService mPaymentService;

    @Autowired
    private PayPassCodeDao   payPassCodeDao;

    @Autowired
    private FErrorLogService fErrorLogService;

    @Scheduled(cron = "0 0 0 * * ?") // 每天凌晨触发一次
    public void scheduleMethod() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String star = sdf.format(new Date());
        long startTime = System.currentTimeMillis();
        logger.info(star + " -开始每天用户支付密码错误次数清零任务");
        try {
            payPassCodeDao.updateErroCount();
            String end = sdf.format(new Date());
            logger.info(end + " -重置用户支付密码错误次数成功");
        } catch (Exception e) {
            e.printStackTrace();
            String end = sdf.format(new Date());
            logger.info(end + " -重置用户支付密码错误操作错误");
            ErrorLog(e, end + "PayPasswordSchedule");
        } finally {
            long endTime = System.currentTimeMillis();
            float seconds = (endTime - startTime) / 1000F;
            String end = sdf.format(new Date());
            logger.info(end + " -重置用户支付密码错误次数完成 耗时"+Float.toString(seconds)+ " seconds.");
        }


    }

    /**
     * 对账单
     * @throws Exception
     */
   // @Scheduled(cron = "0 0 1 * * ?") // 每天凌晨1点触发一次
    public void scheduleUpdateBill() throws Exception {
        Calendar cal   =   Calendar.getInstance();
        cal.add(Calendar.DATE,   -1);
        Date time = cal.getTime();
        try {
            mPaymentService.updateMpayData(time);
        } catch (Exception e) {
            ErrorLog(e,"对账数据更新失败");
            e.printStackTrace();
        }
    }

    public void ErrorLog(Exception e, String... params) {
        FErrorLog errorLog = new FErrorLog();
        errorLog.setErrName(params.length == 0 ? null : params[0]);
        errorLog.setErrData(params.length < 2 ? null : params[1]);
        if (e != null) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            errorLog.setErrContent(sw.toString());
        }
        fErrorLogService.insert(errorLog);
    }

}
